/**
 * @Description: vite配置
 * @Author BPF
 * @create 2021/1/3 17:26
 */
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import legacy from '@vitejs/plugin-legacy'
import vitePluginHtml from 'vite-plugin-html'
import { resolve } from 'path'
import proxyConfig from './src/proxy.js'
import styleImport, { VantResolve } from 'vite-plugin-style-import'
import { viteCommonjs } from '@originjs/vite-plugin-commonjs'
import viteCompression from 'vite-plugin-compression'

/**
 * 动态的插入ejs html
 * @type {{css: *[], external: string[], title: string, script: string[]}}
 */
const inject = {
  external: ['vue', 'vue-router', 'vuex', 'axios', '@bianpengfei/utils', 'vconsole'],
  gzip: false, // 是否开启gzip
  script: [
    'https://cdn.jsdelivr.net/npm/vue@3.2.25/dist/vue.global.min.js',
    'https://cdn.jsdelivr.net/npm/vue-router@4.0.12/dist/vue-router.global.min.js',
    'https://cdn.jsdelivr.net/npm/vuex@4.0.2/dist/vuex.global.min.js',
    'https://cdn.jsdelivr.net/npm/axios@0.24.0/dist/axios.min.js',
    'https://cdn.jsdelivr.net/npm/@bianpengfei/utils@1.0.3/dist/b-utils.min.js',
    'https://cdn.jsdelivr.net/npm/vconsole@3.3.4/dist/vconsole.min.js'
  ],
  css: [],
  title: 'vue3.x移动端模版'
}

export default defineConfig(({ mode }) => {
  const IS_DEV = mode === 'development'
  const IS_PRO = mode === 'production'
  const publicPath = IS_PRO ? '/' : '/' // fr/pc-template-vite/
  return {
    server: {
      host: '0.0.0.0',
      port: 2829,
      open: true,
      cors: true,
      proxy: {
        // 下面是选项写法，例子
        '/api': {
          target: 'http://jsonplaceholder.typicode.com',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, '')
        },
        ...Object.values(proxyConfig.proxy).reduce((pre, cur) => ({ ...pre, [cur['prefix']]: cur['rule'] }), {})
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          charset: false,
          additionalData: `` // '@import "./src/style/app/common.scss";' // 添加公共样式
        },
        less: {
          charset: false,
          javascriptEnabled: true,
          modifyVars: {
            // 用于全局导入，以避免需要单独导入每个样式文件。
            // reference:  避免重复引用
            hack: `true; @import (reference) "${resolve('src/libs/style/app/variables.less')}";
                         @import (reference) "${resolve('src/libs/style/app/transition.less')}";
                         @import (reference)"${resolve('src/libs/style/app/mixin.less')}";`
          }
        }
      }
    },
    resolve: {
      alias: {
        // vue: 'vue/dist/vue.esm-bundler.js',
        '@': resolve(__dirname, 'src'),
        '~libs': resolve(__dirname, 'src/libs'),
        '+libs': resolve(__dirname, 'src/libs'),
        '~vuex-helper': resolve(__dirname, 'src/store/plugins/vuex-helper.js')
      },
      extensions: ['.vue', '.mjs', '.js', '.ts', '.jsx', '.tsx', '.json']
    },
    define: {
      'process.env.NODE_ENV': JSON.stringify(mode),
      PUBLIC_URL: JSON.stringify(String(publicPath)) // 所有加载js文件动态前缀
    },
    plugins: [
      vue(),
      viteCommonjs(),
      vitePluginHtml({
        minify: {
          collapseBooleanAttributes: false,
          collapseWhitespace: false,
          removeAttributeQuotes: false,
          removeComments: false
        },
        inject: {
          data: {
            title: inject.title,
            injectScript: IS_PRO ? inject.script.filter(Boolean) : [],
            injectCss: IS_PRO ? inject.css.filter(Boolean) : []
          }
        }
      }),
      legacy({
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'] // 面向IE11时需要此插件
      }),
      styleImport({
        resolves: [VantResolve()],
        libs: [
          {
            libraryName: 'vant',
            esModule: true,
            resolveStyle: name => `vant/es/${name}/style/index`
          }
        ]
      }),
      IS_DEV && [],
      IS_PRO && [inject.gzip && viteCompression()]
    ]
      .flat(Infinity)
      .filter(Boolean),
    build: {
      rollupInputOptions: {
        external: inject.external
      },
      commonjsOptions: {
        transformMixedEsModules: true
      },
      brotliSize: false,
      terserOptions: {
        compress: {
          drop_console: false, // 是否去除console, 建议在开发环境开启，生产到线上去除
          drop_debugger: true // 删除debugger;语句
        }
      }
    }
  }
})
